#    Copyright 2012 New Mexico EPSCoR
#
#    This file is part of Teacher's P.E.T.
#
#    Teacher's P.E.T. is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Teacher's P.E.T. is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Teacher's P.E.T..  If not, see <http://www.gnu.org/licenses/>.

from models import Activity, Subactivity
from apps.course.models import Course
from apps.course.functions import course_reverse
from apps.participants.models import CourseParticipant

import datetime
import logging
import re
from collections import OrderedDict

logger = logging.getLogger('pet.apps.assignments.context_processor')
def html_title(string):
    from django.template.defaultfilters import title
    """ This makes sure no html entity references were capitalized in django's titlecase fxn """
    return re.sub("&([A-Z].+?\;)", lambda m: m.group(0).lower(), title(string))

def make_activity_menu_html(dict):
    ReturnString = ""
    list = [(menu,activity) for menu, activity in dict.items() if menu != 'link' and menu != 'index' and menu != 'activity']
    for menu, activity in sorted(list,key=lambda (m,a): a['index']):
        if activity['activity'].content or activity['activity'].show_collection_menu:
            ReturnString += """<li class="active"><a href=""" + activity['link'] + ">" + re.sub('\s', '&'+'nbsp;', html_title(menu)) + "</a>\n"
        else:
            ReturnString += """<li class="active"><a>""" + re.sub('\s', '&'+'nbsp;', html_title(menu)) + "</a>\n"
        if len(activity.keys()) > 1:
            ReturnString += "<ul>\n" + make_activity_menu_html(activity) + "</ul>\n"
        ReturnString += "</li>\n"
    return ReturnString

def make_activity_menu(course,dict,list,collection=None):
    for index,activity in enumerate(list):
        display_title = activity.display_title if activity.display_title else activity.title
        kwargs = {'category':activity.category_slug,'title':activity.title_slug}
        if collection:
            kwargs['collection_category'] = collection.category_slug
            kwargs['collection_title'] = collection.title_slug
        dict[display_title.capitalize()] = OrderedDict({'index':index,'activity':activity,'link':course_reverse('apps.activities.views.view',course,**kwargs)}.items())
        SubactivityObjects = activity.get_subactivities()
        if SubactivityObjects:
            make_activity_menu(course,dict[display_title.capitalize()],SubactivityObjects,collection if collection else activity)

def activities(request):
    TheCourse = Course.RequestCourse(request)
    if not TheCourse: return ''
    
    course = TheCourse.course_id

    Objects = None
    TheUser = request.user
    TheCourseParticipant = CourseParticipant.find(course=course,user=TheUser)
    if TheUser and (TheCourseParticipant or TheUser.is_superuser):
        Objects = Activity.find(course, start_date=datetime.datetime.now())
    else:
        Objects = Activity.find(course,is_public=True, start_date=datetime.datetime.now())
    
    MenuDict = OrderedDict()
    if Objects:
        Objects = sorted(Objects,key=lambda item: item.order_number if item.order_number else 1000)
        for activity in Objects:
            if activity.main_menu: make_activity_menu(course,MenuDict,[activity])
    return_html = make_activity_menu_html(MenuDict)
    
    return {'ActivityMenu':return_html}
